﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Silent.API.LastFm.Model;

namespace Silent.API.LastFm
{
    public static class Utility
    {
        public static string ComputeHash(string input)
        {
            var md5 = MD5.Create();
            var inputBytes = Encoding.ASCII.GetBytes(input);
            var hash = md5.ComputeHash(inputBytes);

            var builder = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
                builder.Append(hash[i].ToString("X2"));
            return builder.ToString();
        }
        public static DateTime FromUnixTime(long unixTime)
        {
            return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(unixTime).ToLocalTime();
        }
        public static string GetSignature(Session session, string method)
        {
            var parameters = new List<string>
                {
                    QueryConstants.PREFIX_API_KEY, session.ApiKey,
                    QueryConstants.PREFIX_METHOD, method,
                    QueryConstants.PREFIX_TOKEN, session.Token,
                    session.Secret
                };
            return GetSignature(parameters);
        }
        public static string GetSignature(IEnumerable<string> parameters)
        {
            var parametersEncoded = parameters.Select(x => Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(x)));
            var signature = parametersEncoded.Aggregate(string.Empty, (current, parameter) => current + parameter);
            var hash = ComputeHash(signature);
            return hash;
        }
    }
}
